use sysinfo::{Pid, ProcessExt, System, SystemExt};
use serde_json;
use std::path::PathBuf;

#[derive(Debug, Serialize, Deserialize)]
pub struct ProcessInfo {
    pub pid: i32,
    pub model: String,
    pub start_time: u64,
    pub command: String,
}

pub fn list_running_models() -> Vec<ProcessInfo> {
    let mut system = System::new();
    system.refresh_processes();
    
    system.processes()
        .iter()
        .filter_map(|(&pid, process)| {
            if process.cmd().iter().any(|arg| arg.contains("yam run")) {
                Some(ProcessInfo {
                    pid: pid.as_u32() as i32,
                    model: process.cmd().join(" "),
                    start_time: process.start_time(),
                    command: process.cmd().join(" "),
                })
            } else {
                None
            }
        })
        .collect()
}

pub fn save_process_info(info: &ProcessInfo) -> Result<(), std::io::Error> {
    let runtime_dir = dirs::runtime_dir().unwrap_or_else(|| PathBuf::from("/tmp"));
    let file_path = runtime_dir.join(format!("yam_{}.json", info.pid));
    let data = serde_json::to_string(info)?;
    std::fs::write(file_path, data)
}